<?php

namespace app\common\model;

use fast\Random;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'marketable_text',
        'is_recommend_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }

    
    public function getMarketableList()
    {
        return ['1' => __('Marketable 1'), '2' => __('Marketable 2')];
    }

    public function getIsRecommendList()
    {
        return ['1' => __('Is_recommend 1'), '2' => __('Is_recommend 2')];
    }


    public function getMarketableTextAttr($value, $data)
    {
        $value = $value ?: ($data['marketable'] ?? '');
        $list = $this->getMarketableList();
        return $list[$value] ?? '';
    }


    public function getIsRecommendTextAttr($value, $data)
    {
        $value = $value ?: ($data['is_recommend'] ?? '');
        $list = $this->getIsRecommendList();
        return $list[$value] ?? '';
    }

    public function setSpesDescAttr($value){
        return $value && is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }

    public function goodscat(){
        return $this->hasOne('GoodsCat', 'id', 'goods_cat_id')->setEagerlyType(0);

    }
}
